package com.windoent.yugioh.ui.activity.meinfo;

import android.content.Intent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.baidu.mobstat.StatService;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.windoent.yugioh.MyApplication;
import com.windoent.yugioh.R;
import com.windoent.yugioh.adapter.banner.ImageAdapter;
import com.windoent.yugioh.adapter.brvah.multi.JoinGamePlayersMultiAdapter;
import com.windoent.yugioh.base.BaseActivity;
import com.windoent.yugioh.bean.JingWeiBean;
import com.windoent.yugioh.bean.JoinPlayerBean;
import com.windoent.yugioh.bean.SaiShiDetailsBean;
import com.windoent.yugioh.help.map.OpenMapUtil;
import com.windoent.yugioh.help.recycle.GridSpaceItemDecoration;
import com.windoent.yugioh.http.PhoneLive;
import com.windoent.yugioh.ui.activity.saishi.ConTestationListActivivty;
import com.windoent.yugioh.ui.activity.saishi.CreateGamesActivity;
import com.windoent.yugioh.utils.BaseMethod;
import com.windoent.yugioh.utils.BaseUtils;
import com.windoent.yugioh.utils.ToastUtils;
import com.windoent.yugioh.widget.ActivityTitle;
import com.windoent.yugioh.widget.MessageItem;
import com.youth.banner.Banner;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

/**
 * author : robert
 * date   : 2021/5/11 15:27
 * desc   :比赛管理详情
 */
public class GameManagerPaidDetialsActivity extends BaseActivity {
    private ActivityTitle mActivityTitle;
    private MessageItem mItemMsg;

    private Button mBtnGetCode;
    private TextView mTvLocationName;
    private TextView mTvDetailTime;
    private TextView mTvDianpu;
    private RecyclerView mRecyclerView;
    private Banner mBanner;
    private ImageAdapter bannerAdapter;
    private TextView mTvFormat;
    private TextView mTvCost;
    private TextView mTvPrize;
    private TextView mTvTellphone;
    private TextView mTvRemark;
    private SmartRefreshLayout mSmartLayout;
    private RelativeLayout mRlRv;

    private SaiShiDetailsBean.DataBean.InfoBean info;
    private String id = "";
    private boolean signup = false;//选手是否包名
    private int status;//1审核中2报名中3开始比赛4开始瑞士轮5开启淘汰赛
    private String role = "";
    private JoinGamePlayersMultiAdapter adapter;
    private int isOnlinePayment;
    private TextView mTvHuanjing;
    private TextView mTvSaizhi;


    @Override
    public int getLayout() {
        return R.layout.activity_game_manager_paid_details;
    }

    @Override
    public void initView() {
        super.initView();
        mActivityTitle = (ActivityTitle) findViewById(R.id.activity_title);
        immersiveStatusBar(mActivityTitle.getView());

        mItemMsg = (MessageItem) findViewById(R.id.item_msg);
        mBtnGetCode = (Button) findViewById(R.id.btn_get_code);
        mBanner = (Banner) findViewById(R.id.banner);
        mTvLocationName = (TextView) findViewById(R.id.tv_location_name);
        mTvDetailTime = (TextView) findViewById(R.id.tv_detail_time);
        mTvDianpu = (TextView) findViewById(R.id.tv_dianpu);
        mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        mTvFormat = (TextView) findViewById(R.id.tv_format);
        mTvCost = (TextView) findViewById(R.id.tv_cost);

        mTvPrize = (TextView) findViewById(R.id.tv_prize);
        mTvTellphone = (TextView) findViewById(R.id.tv_tellphone);
        mTvRemark = (TextView) findViewById(R.id.tv_remark);
        mSmartLayout = (SmartRefreshLayout) findViewById(R.id.smart_layout);
        mTvHuanjing = (TextView) findViewById(R.id.tv_huanjing);
        mTvSaizhi = (TextView) findViewById(R.id.tv_saizhi);
        mRlRv = (RelativeLayout) findViewById(R.id.rl_rv);
    }

    @Override
    public void initData() {
        super.initData();
        id = getIntent().getStringExtra("id");
        initAdapter();
        initBanner();
        mItemMsg.setListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(mContext, MyMsgActivity.class);
                startActivity(intent);
            }
        });
        //下拉刷新
        initFresh();
        fresh(id);
    }

    private void initBanner() {
        bannerAdapter = new ImageAdapter(null);
        mBanner.setAdapter(bannerAdapter)
                .addBannerLifecycleObserver(this);//添加生命周期观察者

    }

    private void initAdapter() {
        GridLayoutManager manager = new GridLayoutManager(mContext, 12);
        GridSpaceItemDecoration decoration = new GridSpaceItemDecoration(mContext);
        int itemDecorationCount = mRecyclerView.getItemDecorationCount();
        if (itemDecorationCount > 0) {
            mRecyclerView.removeItemDecorationAt(0);
        }
        mRecyclerView.addItemDecoration(decoration);
        mRecyclerView.setLayoutManager(manager);
        adapter = new JoinGamePlayersMultiAdapter();
        mRecyclerView.setAdapter(adapter);
        mRecyclerView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return mRlRv.onTouchEvent(event);
            }
        });
    }

    @Override
    public void initListener() {
        super.initListener();
        mActivityTitle.setBackListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        mRlRv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(mContext, ConTestationListActivivty.class);
                intent.putExtra("id", id);
                startActivity(intent);
            }
        });
        mBtnGetCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                /**
                 * "customer":"商家",
                 * "customerReferee":"商家+主裁判",
                 * "notJoin":"没有参加",
                 * "pReferee":"主裁判",
                 * "player":"选手",
                 * "referee":"裁判",
                 * "visitor":"游客"
                 */
                boolean notJoin = BaseMethod.notNull(role) && role.equals("notJoin");
                boolean pReferee = BaseMethod.notNull(role) && role.equals("pReferee");
                boolean player = BaseMethod.notNull(role) && role.equals("player");
                boolean referee = BaseMethod.notNull(role) && role.equals("referee");
                boolean customer = BaseMethod.notNull(role) && role.equals("customer");
                boolean customerReferee = BaseMethod.notNull(role) && role.equals("customerReferee");
                boolean pending = BaseMethod.notNull(role) && role.equals("pending");
                if (customer || customerReferee) {
                    if (status == 11) {
                        //重新提交
                        Intent intent = new Intent(mContext, CreateGamesActivity.class);
                        startActivity(intent);
                    } else if (status == 1) {
                        BaseMethod.showSucessDialog(mContext, getString(R.string.string_reviewing_feedback_three_days), null);
                    }
                }
            }
        });
        mTvLocationName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (info != null) {
                    SaiShiDetailsBean.DataBean.InfoBean.BasicInfoBean basic_info = info.getBasic_info();
                    if (basic_info != null) {
                        String address_position = basic_info.getAddress_position();
                        if (BaseUtils.isJSONValid(address_position)) {
                            JingWeiBean json = gson.fromJson(address_position, JingWeiBean.class);
                            if (json != null && BaseMethod.notNull(json.getLatitude()) && BaseMethod.notNull(json.getLongitude())) {
                                OpenMapUtil.openMapPopupWindow(GameManagerPaidDetialsActivity.this, mTvLocationName, basic_info.getAddress(), BaseUtils.stringToDouble(json.getLatitude()), BaseUtils.stringToDouble(json.getLongitude()));
                            } else
                                ToastUtils.showText(getString(R.string.string_latitude_logtitude_no_data));
                        } else
                            ToastUtils.showText(getString(R.string.string_latitude_logtitude_no_data));
                    } else
                        ToastUtils.showText(getString(R.string.string_latitude_logtitude_no_data));
                } else ToastUtils.showText(getString(R.string.string_latitude_logtitude_no_data));
            }
        });
    }

    private void initFresh() {
        mSmartLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                fresh(id);
            }
        });
    }

    //刷新状态
    private void fresh(String id) {
        getDetailsSaiShiData(id);
    }

    private void getDetailsSaiShiData(String id) {
        showLoadingDialog("");
        PhoneLive.getDetailsSaiShiData(getUserToken(), id, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                hideLoadingDialog();
                ToastUtils.showText(e.getMessage());
                mSmartLayout.finishRefresh(false);
            }

            @Override
            public void onResponse(String response, int id) {
                hideLoadingDialog();
                if (BaseUtils.isJSONValid(response)) {
                    try {
                        if (BaseUtils.codeIs0(mContext, response)) {
                            mSmartLayout.finishRefresh(true);
                            SaiShiDetailsBean json = gson.fromJson(response, SaiShiDetailsBean.class);
                            if (json != null) {
                                SaiShiDetailsBean.DataBean data = json.getData();
                                if (data != null) {
                                    info = data.getInfo();
                                    signup = data.isSignup();
                                    role = data.getRole();
                                    if (info != null) {
                                        status = info.getStatus();
                                        isOnlinePayment = info.getIsOnlinePayment();
                                        showButtonStyle(role, status);
                                        List<String> banner = info.getBanner();
                                        if (bannerAdapter != null &&banner != null && banner.size() > 0) {
                                            mBanner.setVisibility(View.VISIBLE);
                                            bannerAdapter.setDatas(banner);
                                            bannerAdapter.notifyDataSetChanged();
                                        } else {
                                            mBanner.setVisibility(View.GONE);
                                        }
                                        initUi(info);
                                        SaiShiDetailsBean.DataBean.InfoBean.PlayerBean player = info.getPlayer();
                                        if (player != null) {
                                            List<String> player_images = player.getPlayer_images();
                                            String stringCount = BaseMethod.notNullDefaultValueNull(player.getSign_count() + "/" + player.getPlayer_count());
                                            if (player_images != null && player_images.size() > 10) {
                                                List<String> list = player_images.subList(0, 10);
                                                if (adapter != null)
                                                    adapter.setNewInstance(getPlayersMulDataBean(list, stringCount));
                                            } else {
                                                if (adapter != null)
                                                    adapter.setNewInstance(getPlayersMulDataBean(player_images, stringCount));
                                            }
                                        }
                                    }
                                }
                            }
                        } else mSmartLayout.finishRefresh(false);
                    } catch (JSONException e) {
                        mSmartLayout.finishRefresh(false);
                        e.printStackTrace();
                    }
                } else {
                    mSmartLayout.finishRefresh(false);
                    ToastUtils.showText(getString(R.string.string_response_error));
                }
            }
        });
    }

    //选手
    private List<JoinPlayerBean> getPlayersMulDataBean(List<String> list, String stringCount) {
        List<JoinPlayerBean> arrayList = new ArrayList<>();
        if (list != null && list.size() > 0) {
            arrayList.clear();
            for (int i = 0; i < list.size(); i++) {
                JoinPlayerBean bean = new JoinPlayerBean();
                bean.setItemType(0);
                bean.setString(list.get(i));
                arrayList.add(bean);
            }
            JoinPlayerBean bean = new JoinPlayerBean();
            bean.setItemType(1);
            bean.setString(stringCount);
            arrayList.add(bean);
        } else {
            arrayList.clear();
            JoinPlayerBean bean = new JoinPlayerBean();
            bean.setItemType(1);
            bean.setString(stringCount);
            arrayList.add(bean);
        }
        return arrayList;
    }

    //刷新ui
    private void initUi(SaiShiDetailsBean.DataBean.InfoBean info) {
        SaiShiDetailsBean.DataBean.InfoBean.BasicInfoBean basic_info = info.getBasic_info();
        SaiShiDetailsBean.DataBean.InfoBean.DescInfoBean desc_info = info.getDesc_info();
        SaiShiDetailsBean.DataBean.InfoBean.PlayerBean player = info.getPlayer();
        if (basic_info != null) {
            setText(mTvLocationName, BaseMethod.notNullDefaultValueNull(basic_info.getAddress_info()));
            setText(mTvDetailTime, BaseMethod.notNullDefaultValueNull(basic_info.getStart_at()));
            setText(mTvDianpu, BaseMethod.notNullDefaultValueNull(basic_info.getCustomer_name()));//主办方
        }
        setText(mTvHuanjing, getConditionName(info.getCondition()));
        setText(mTvFormat, getTypeName(info.getType()));
        if (desc_info != null) {
            setText(mTvSaizhi, BaseMethod.notNullDefaultValueNull(desc_info.getRule_display()));
            setText(mTvCost, BaseMethod.notNullDefaultValueNull(desc_info.getCost() + ""));
            setText(mTvTellphone, BaseMethod.notNullDefaultValueNull(desc_info.getContact()));
            setText(mTvPrize, BaseMethod.notNullDefaultValueNull(desc_info.getPrize_desc()));
            setText(mTvRemark, BaseMethod.notNullDefaultValueNull(desc_info.getRemarks()));
        }
    }

    private String getRuleName(int rule, int round, int wining) {
        //赛制1：瑞士轮 2：淘汰赛 3瑞士轮+淘汰赛 round轮 wining 出几强
        if (BaseMethod.notNull(rule + "") && rule == 1) {
            return getString(R.string.string_game_ruishilun) + round + getString(R.string.string_game_lun);
        }
        if (BaseMethod.notNull(rule + "") && rule == 2) {
            return getString(R.string.string_knock_out);
        }
        if (BaseMethod.notNull(rule + "") && rule == 3) {
            return getString(R.string.string_game_ruishilun) + round + getString(R.string.string_game_lun) + getString(R.string.string_game_chu) + wining + getString(R.string.string_game_qiang);
        }
        return "";
    }

    private String getConditionName(int condition) {
        //比赛环境（1：简体中文赛2：OCG）
        if (BaseMethod.notNull(condition + "") && condition == 1) {
            return getString(R.string.string_chinese_simple_environment);
        }
        if (BaseMethod.notNull(condition + "") && condition == 2) {
            return getString(R.string.string_ocg_environment);
        }
        return "";
    }

    private String getTypeName(int type) {
        //赛事类型 (1:娱乐赛2：积分赛)3：特殊赛4：巡回赛
        if (BaseMethod.notNull(type + "") && type == 1) {
            return getString(R.string.string_entertainment_race);
        }
        if (BaseMethod.notNull(type + "") && type == 2) {
            return getString(R.string.string_point_race);
        }
        if (BaseMethod.notNull(type + "") && type == 3) {
            return getString(R.string.string_teshu_race);
        }
        if (BaseMethod.notNull(type + "") && type == 4) {
            return getString(R.string.string_xunhui_race);
        }
        return "";
    }

    /**
     * 底部按钮
     * "customer":"商家",
     * "customerReferee":"商家+主裁判",
     * "notJoin":"没有参加",
     * "pReferee":"主裁判",
     * "player":"选手",
     * "referee":"裁判",
     * "visitor":"游客"
     * "pending":"审核中"
     */
    private void showButtonStyle(String role, int status) {
        boolean notJoin = BaseMethod.notNull(role) && role.equals("notJoin");
        boolean pReferee = BaseMethod.notNull(role) && role.equals("pReferee");
        boolean player = BaseMethod.notNull(role) && role.equals("player");
        boolean referee = BaseMethod.notNull(role) && role.equals("referee");
        boolean customer = BaseMethod.notNull(role) && role.equals("customer");
        boolean customerReferee = BaseMethod.notNull(role) && role.equals("customerReferee");
        boolean pending = BaseMethod.notNull(role) && role.equals("pending");
        if (customer || customerReferee) {
            //店家 1审核中,11审核不通过
            mBtnGetCode.setVisibility(status == 1 || status == 11 ? View.VISIBLE : View.GONE);
            if (status == 1) {
                mBtnGetCode.setSelected(true);
                mBtnGetCode.setText(getString(R.string.string_reviewing));
            } else if (status == 11) {
                mBtnGetCode.setSelected(false);
                mBtnGetCode.setText(getString(R.string.string_auth_unpass));
            }
        } else {
            mBtnGetCode.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        StatService.onPageStart(this, "比赛管理支付详情界面");
        if (mItemMsg != null) {
            mItemMsg.setTvTitle(MyApplication.getInstance().getMsgNumber());
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        StatService.onPageEnd(this, "比赛管理支付详情界面");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkHttpUtils.getInstance().cancelTag(this);
    }
}
